package com.yozinga.fragment;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.os.Bundle;
import android.provider.Settings;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.yozinga.R;
import com.yozinga.model.BaseModel.OnRequestFinishedCallback;
import com.yozinga.model.CreateAppModel;
import com.yozinga.service.Actions;
import com.yozinga.util.AppData;
import com.yozinga.util.SharedData;
import com.yozinga.util.ToolKit;

public class NotificationsFragment extends BaseFragment implements OnClickListener,OnTimeSetListener,OnRequestFinishedCallback{

	SharedData sharedData; 
	boolean mToggleStauts;
	TextView mStartTime,mEndTime;
	String mStartTimeValue,mEndTimeValue;
	private TextView mPickerButton;
	CreateAppModel createAppModel;
	int mRadiusCount;
	TextView tvRadius;
	Activity mActivity;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_notifications, container,false);
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mActivity = activity;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);


		sharedData = new SharedData(getActivity());
		Button saveButton = (Button) getActivity().findViewById(R.id.save);
		saveButton.setVisibility(View.VISIBLE);

		//Toggle Status
		mToggleStauts = sharedData.getpushNotification();
		ImageView toggle = (ImageView) getView().findViewById(R.id.tgOnOff);
		if(mToggleStauts){
			((ImageView) getView().findViewById(R.id.tgOnOff)).setImageResource(R.drawable.onbutton);
		}else{
			((ImageView) getView().findViewById(R.id.tgOnOff)).setImageResource(R.drawable.offbutton);
		}
		toggle.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(!mToggleStauts){
					mToggleStauts = true;
					((ImageView) getView().findViewById(R.id.tgOnOff)).setImageResource(R.drawable.onbutton);
				}else{
					mToggleStauts = false;
					((ImageView) getView().findViewById(R.id.tgOnOff)).setImageResource(R.drawable.offbutton);
				}
			}
		});

		//Start Time
		mStartTime = (TextView)getView().findViewById(R.id.startTime);
		((LinearLayout) getActivity().findViewById(R.id.startTimeLayout)).setOnClickListener(this);
		mStartTime.setText(sharedData.getStartTime());

		//End Time
		mEndTime = (TextView)getView().findViewById(R.id.endTime);
		((LinearLayout) getActivity().findViewById(R.id.endTimeLayout)).setOnClickListener(this);
		mEndTime.setText(sharedData.getEndTime());

		//Radius
		mRadiusCount = Integer.parseInt(sharedData.getRadius());

		tvRadius = (TextView)getView().findViewById(R.id.tvRadius);
		tvRadius.setText(Integer.toString(mRadiusCount));
		((ImageView)getView().findViewById(R.id.uparrow)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				mRadiusCount++;
				tvRadius.setText(Integer.toString(mRadiusCount));
			}
		});
		((ImageView)getView().findViewById(R.id.downarrow)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(mRadiusCount>0)
					mRadiusCount--;
				tvRadius.setText(Integer.toString(mRadiusCount));
			}
		});

		Button but = (Button) getActivity().findViewById(R.id.save);
		but.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				saveDetails(mActivity);				
			}
		});
	}	

	@Override
	public void onClick(View view) {

		if(view.getId() == R.id.startTimeLayout){
			String timeString;
			if (mStartTime.getText() != null && !mStartTime.getText().toString().equalsIgnoreCase("")) {
				timeString = mStartTime.getText().toString();
			} else {
				timeString = "0";
			}
			mPickerButton = mStartTime;
			timePicker(timeString);
		}else if(view.getId() == R.id.endTimeLayout){
			String timeString;
			if (mEndTime.getText() != null && !mEndTime.getText().toString().equalsIgnoreCase("")) {
				timeString = mEndTime.getText().toString();
			} else {
				timeString = "0";
			}
			mPickerButton = mEndTime;
			timePicker(timeString);
		}

	}

	public void saveDetails(Activity activity){
		if(mToggleStauts){
			mActivity = activity;
			ToolKit.startProgress(activity, R.string.loading);
			createAppModel = new CreateAppModel(activity);
			createAppModel.addOnServiceRequestCompletedListener(this);
			Bundle bundle = new Bundle();
			String deviceId = Settings.Secure.getString(activity.getContentResolver(), 
					Settings.Secure.ANDROID_ID);
			Log.i("Today","Device ID is: "+deviceId+"askfd"+"3E08072BA53852F0");
			bundle.putString("DeviceId",deviceId);
			bundle.putString("DeviceType", "Android");
			bundle.putDouble("Latitude", Double.parseDouble("17.441287"));
			bundle.putDouble("Longitude", Double.parseDouble("78.3956767"));
			bundle.putBoolean("PushNotification",mToggleStauts);
			bundle.putString("StartTime",mStartTime.getText().toString());
			bundle.putString("EndTime",mEndTime.getText().toString());
			createAppModel.createUpdateApp(AppData.UPDATE_APP, bundle, Actions.ACTION_UPDATE_APP);
		}else{
			Toast.makeText(activity, "Please Activate Push Notifications", Toast.LENGTH_LONG).show();
		}
	}

	private void timePicker(String timeString){

		/**
		 * Converting String to date
		 */
		Date timeDate = breakingTimeFormat(timeString);
		Calendar timeCalendar = Calendar.getInstance();
		timeCalendar.setTime(timeDate);
		int hour = timeCalendar.get(Calendar.HOUR_OF_DAY);
		int minute = timeCalendar.get(Calendar.MINUTE);
		TimePickerDialog td = new TimePickerDialog(getActivity(), this, hour, minute,
				DateFormat.is24HourFormat(getActivity()));
		td.show();
	}


	@Override
	public void onRequestFinished(int resultCode, Bundle payload) {
		sharedData.setDeviceSettings(mStartTime.getText().toString(), mEndTime.getText().toString(), mToggleStauts,Integer.toString( mRadiusCount));
		//String response = payload.getString("ServiceResponse");
		Log.i("Today","UpdateApp Respons is :"+payload.getString("ServiceResponse"));
		Toast.makeText(mActivity, "Settings Updated", Toast.LENGTH_LONG).show();
		ToolKit.stopprogess();
	}

	@Override
	public void onPause() {
		super.onPause();
		if(createAppModel!=null)
			createAppModel.removeOnServiceRequestCompleteListener(this);
	}
	@Override
	public void onTimeSet(TimePicker view, int arg1, int arg2) {

		Date d = null;
		String time;
		/**
		 * Used to change the time string basedon device time format, in order to parse the required time format
		 */
		if (!DateFormat.is24HourFormat(getActivity())) {
			if (arg1 >= 12) {
				int timeValue = arg1 - 12;
				time = timeValue + ":" + arg2 + " PM";
			} else {
				time = arg1 + ":" + arg2 + " AM";
			}

		} else {
			time = arg1 + ":" + arg2;
		}
		try {
			d = (ToolKit.timeFormat(getActivity()).parse(time));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mStartTimeValue = ToolKit.timeFormat(getActivity()).format(d);
		mPickerButton.setText(mStartTimeValue);
	}

	/**
	 * Convert stringtime to date in order to set hour and min for Datepickerdialog
	 */
	public Date breakingTimeFormat(String date) {
		Date hourDt = null;
		/**
		 * Used to change the time string basedon device time format, in order to parse the required time format
		 */
		if (!DateFormat.is24HourFormat(getActivity())) {
			if(date.equalsIgnoreCase("0"))
			{
				date = "12:00 AM";
			}
		} else if(date.equalsIgnoreCase("0")){
			date = "0";
		}

		try {
			hourDt = ToolKit.timeFormat(getActivity()).parse(date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return hourDt;
	}
}
